package servlet;

import DAO.UserDao;
import Utils.CookieUtils;
import bean.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet(name = "infoChange", value = "/infoChange")
@MultipartConfig(
    fileSizeThreshold=1024*1024*2,    // 2MB
    maxFileSize=1024*1024*10,         // 10MB
    maxRequestSize=1024*1024*50       // 50MB
)
public class infoChange extends HttpServlet {
    public UserDao userDao = new UserDao();
    
    public void delete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        User user = (User)request.getSession().getAttribute("user");
        userDao.deleteUserByID(user.getUsername());
        CookieUtils.deleteCookie(request.getCookies(),"username",response);
        response.sendRedirect("index.jsp");
    }
    
    public void change(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 获取当前登录用户
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect("index.jsp");
                return;
            }

            // 获取表单数据
            String name = request.getParameter("name");
            String email = request.getParameter("email");

            // 处理头像上传
            Part avatarPart = request.getPart("avatar");
            String newAvatarFileName = user.getAvatar(); // 默认使用原头像

            if (avatarPart != null && avatarPart.getSize() > 0) {
                // 生成新文件名：时间戳_原文件名
                String originalFileName = avatarPart.getSubmittedFileName();
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                String fileName = System.currentTimeMillis() + fileExtension;
                
                // 设置保存路径
                String uploadPath = request.getServletContext().getRealPath("/static/img/头像/");
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                // 删除旧头像文件
                if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                    File oldAvatar = new File(uploadPath + File.separator + user.getAvatar());
                    if (oldAvatar.exists()) {
                        oldAvatar.delete();
                    }
                }

                // 保存新头像文件
                String fullFilePath = uploadPath + File.separator + fileName;
                avatarPart.write(fullFilePath);
                
                // 更新头像文件名
                newAvatarFileName = fileName;
            }

            // 更新用户信息
            user.setName(name);
            user.setEmail(email);
            user.setAvatar(newAvatarFileName);

            // 保存到数据库
            int result = userDao.updateUser(user);
            if (result > 0) {
                // 更新session中的用户信息
                request.getSession().setAttribute("user", user);
                response.sendRedirect("info.jsp");
            } else {
                throw new Exception("更新数据库失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新个人信息失败：" + e.getMessage());
            request.getRequestDispatcher("info.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            String action = request.getParameter("action");
            Method method = this.getClass().getMethod(action, 
                HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
}
